//
// Created by Administrator on 2021/11/10.
//

#include "Application.h"

Application* Application::m_App = nullptr;

Application::Application(const std::string& title, int width, int height)
    : m_Title(title),
      m_Width(width),
      m_Height(height)
{
    m_App = this;

    // init glfw
    ThrowIfFailed(glfwInit());

    // create window
    m_Window = glfwCreateWindow(m_Width, m_Height, m_Title.c_str(), nullptr, nullptr);
    ThrowIfFailed(m_Window);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwMakeContextCurrent(m_Window);

    // add event callback
    glfwSetFramebufferSizeCallback(m_Window, OnGlfwFramebufferSizeChanged);
    glfwSetKeyCallback(m_Window, OnGlfwKeyCallback);

    // init opengl
    ThrowIfFailed(gladLoadGLLoader(GLADloadproc(glfwGetProcAddress)));
}

Application::~Application()
{
    if(m_Window)
    {
        m_Window = nullptr;
    }
    if(m_App)
    {
        m_App = nullptr;
    }
}

void Application::Run()
{
    OnCreate();

    // main loop
    while(!glfwWindowShouldClose(m_Window))
    {
        glfwPollEvents();
        OnUpdate();
        OnRender();
        glfwSwapBuffers(m_Window);
    }

    OnDestroy();
    glfwDestroyWindow(m_Window);
    glfwTerminate();
}